import React from 'react';

export function useCountdown(cb, duration) {
    const callback = React.useRef();

    React.useEffect(
        () => {
            callback.current = cb;
        },
        [cb]
    );
    React.useEffect(
        () => {
            function action() {
                callback.current();
            }

            if (duration) {
                const interval = setInterval(() => {
                    action();
                }, duration);

                return () => clearInterval(interval);
            }
        },
        [duration]
    );
}

/**
 *
 * 如何用
 *
 * function App() {
 *  const [count, setCount] = React.useState(30);
 *
 *  useCountdown(function () {
 *     setCount(count - 1);
    }, 1000);
 */
